package general;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import queryManager.QrelManager;
import queryManager.QrelOutputManager;
import queryManager.Query;
import queryManager.QueryParser;
import queryManager.Requete;
import utils.BDD;


public class Evaluator {

	private HashMap<Integer,ArrayList<Double>> datas ;
	
	public Evaluator() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException{
		datas = new HashMap<Integer, ArrayList<Double>>();
		evaluate();
	}
	
	public void evaluate() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		BDD.getInstance();
		
		//on traite toutes les requetes et on stocke les resultats dans des fichiers
		Requete req = null;
		for(Query q : IHM.queries){
			req = new Requete(q,"sorties");
			req.printInFile();
		}
		
		//on recupere nos resultats
		QrelOutputManager qrelOutputManager = new QrelOutputManager("sorties","^qrel[0-9]+\\.txt$");
		HashMap<Integer,ArrayList<String>> queryOutputResults = qrelOutputManager.getQrels();
		
		//on calcule les precisions
		for(int id : IHM.queryResults.keySet()){
			double a = precision(queryOutputResults.get(id),IHM.queryResults.get(id),5)/5;
			double b = precision(queryOutputResults.get(id),IHM.queryResults.get(id),10)/10;
			double c = precision(queryOutputResults.get(id),IHM.queryResults.get(id),25)/25;
			ArrayList<Double> l = new ArrayList<Double>();
			l.add(a);l.add(b);l.add(c);
			datas.put(id, l);
			
		}

	}
	
	/**
	 * Calcul la precision
	 * @param output : nos resultats
	 * @param qrels : les "vrais" resultats
	 * @param precision : precision à 5, 10 ou 25
	 * @return
	 */
	public static double precision(ArrayList<String> output, HashMap<String ,Integer> qrels,int precision){
		double result=0;
		for (String s : output){
			precision--;
			if(qrels.get(s)==1){
				result++;
			}
			if(precision==0)
				break;
		}
		return result;
	}

	public HashMap<Integer, ArrayList<Double>> getDatas() {
		return datas;
	}

	public void setDatas(HashMap<Integer, ArrayList<Double>> datas) {
		this.datas = datas;
	}
	
	
}
